package edu.olin.scheduler.loader;

import edu.olin.scheduler.common.*;

public class MeetingLoader {
    
    public static final char[] days = { 'S','M','T','W','R','F','A' };
    
    public static Meeting getMeeting(String s) throws ParseException {
        if(s==null){ throw new ParseException("Cannot parse a null meeting"); } //not a valid meeting
        if(s.length()!=9){ throw new ParseException("Invalid meeting: meetings must be 9 characters long"); } //not a valid meeting
        int dow = getDayOfWeek(s.charAt(0));
        SimpleTime start = getSimpleTime(s.substring(1,5));
        SimpleTime end = getSimpleTime(s.substring(5,9));
        return new Meeting(dow,start,end);
        }
    
    private static SimpleTime getSimpleTime(String s) throws ParseException {
        if(s==null){ throw new ParseException("Cannot parse a null time"); }
        if(s.length()!=4){ throw new ParseException("times must be 4 digits long, in hhmm 24-hour format"); }
        if(!s.matches("[0-9]+")){ throw new ParseException("time must contain only digits"); }
        int hours = getInt(s.substring(0,2));
        int minutes = getInt(s.substring(2,4));
        return new SimpleTime(hours,minutes);
        }
    
    private static int getInt(String s) throws ParseException {
        try{ return Integer.parseInt(s); }catch(NumberFormatException nfe){}
        throw new ParseException("Not a valid number: "+s);
        }
    
    private static int getDayOfWeek(char dow) throws ParseException {
        for(int i=0; i<days.length; i++){
            if(dow==days[i]){ return i; }
            }
        throw new ParseException("Invalid day of week");
        }
    
}
